package com.example.balancedparentheses;

import java.util.LinkedList;

public class BalancedParentheses {

    public static  boolean checkBalanced(String line) {
        LinkedList<Integer> list = new LinkedList<>();

        for (int i = 0; i < line.length(); i++) {
            int ch = (int) line.charAt(i);
            if (ch == (int) '{' || ch == (int) '(' || ch == (int) '[') {
                list.offerFirst(ch);
            } else {
                Integer peek = list.peek();
                if (peek == null) {
                    return false;
                }
                if ((peek == (int) '{' && ch == (int) '}') ||
                        (peek == (int) '(' && ch == (int) ')') ||
                        (peek == (int) '[' && ch == (int) ']')) {
                    list.pop();
                } else {
                    return false;
                }
            }

        }
        return list.isEmpty();
    }





    public static boolean isBalanced2(String line) {

        String tmp = line;

        while (true) {
            String replace = replace(tmp);
            if (replace.length() == 0) {
                return true;
            }
            if (replace.equals(tmp)) {
                return false;
            }
            tmp = replace;
        }
    }

    private static String replace(String line) {
        return line.replaceAll("\\{}", "")
                .replaceAll("\\[]", "")
                .replaceAll("\\(\\)", "");
    }
}
